import subApps from '../sub-app.config'

const { APP_ENV } = process.env
const DEFAULT_VERSION = '1.0.0'

export default (htmlTemplate, config = {}) => {

  // 匹配entry js正则
  // 例: <script src="xxx.js" entry app="sub-app" filename="sub-app.index.bundle.js"></script>
  const entryReg = /<script((?!<script)[\s\S])*entry[\s\S]*?><\/script>/g
  const appReg = /app="[\s\S]*?"/g
  const chunkReg = /chunk="[\s\S]*?"/g

  // 获取script属性值
  const getAttrValue = (arr) => {
    let strList = arr[0].split('=')
    return strList[1].replace(/"/g, '')
  }

  try {

    // 获取entry js str
    let matchList = htmlTemplate.match(entryReg)
    if (!matchList || matchList.length === 0) {
      throw('缺少entry script')
    }

    // 获取entry js app attr
    let entryScriptStr = matchList[0]
    let appMatch = entryScriptStr.match(appReg)
    if (!appMatch || appMatch.length === 0) {
      throw('entry script缺少「app」属性')
    }

    let app = getAttrValue(appMatch)

    // 获取chunk 默认为index
    let chunkMatch = entryScriptStr.match(chunkReg)
    let chunkStr = `index`
    if (chunkMatch && chunkMatch.length) {
      chunkStr = getAttrValue(chunkMatch)
    }
    let chunks = chunkStr.split(',')

    // 注意：sub-app.config 子服务中的name 需和script app属性值保持一致！
    // 例如 name="subapp" <scirpt app="subapp"></scirpt>
    let baseurl = '/'
    let filterApp = subApps.filter(item => item.name === app)
    if (filterApp.length) {
      baseurl = filterApp[0].entrys[APP_ENV || 'prod']
    }

    let version = config[`${app}_${APP_ENV || 'prod'}`] || DEFAULT_VERSION

    // 根据chunk 拼接script 将最后一个chunk 当作entry
    let scriptTemp = ''
    chunks.forEach((chunk, i) => {

      let temp = `<script src="${baseurl}${version}/${chunk}.bundle.js" defer></script>`

      if (i === chunks.length -1) {
        temp = `<script src="${baseurl}${version}/${chunk}.bundle.js" defer entry></script>`
      }

      scriptTemp += temp
    })

    return htmlTemplate.replace(entryReg, scriptTemp)
  } catch (error) { 
    console.error(`[base] ${error}`)
    return htmlTemplate 
  }
}